#include "base.h"

static void convertFrameToYUYV(AVFrame* frame, std::ofstream& outputFile) {
    int width = frame->width;
    int height = frame->height;

    // 分配YUYV帧内存
    uint8_t* yuyvData = new uint8_t[width * height * 2];

    AVFrame yuyvFrame;
    av_image_fill_arrays(yuyvFrame.data, yuyvFrame.linesize, yuyvData,
                         AV_PIX_FMT_YUYV422, width, height, 1);

    // 进行YUV格式转换
    struct SwsContext* swsContext = sws_getContext(width, height,
                                                   (AVPixelFormat)frame->format,
                                                   width, height,
                                                   AV_PIX_FMT_YUYV422,
                                                   SWS_BICUBIC, nullptr, nullptr, nullptr);

    if (swsContext) {
        sws_setColorspaceDetails(swsContext, sws_getCoefficients(SWS_CS_ITU601), 0, sws_getCoefficients(SWS_CS_ITU709), 0, 0, 1 << 16, 1 << 16);
    }

    if (!swsContext) {
        std::cout << "无法创建图像转换上下文." << std::endl;
        delete[] yuyvData;
        return;
    }

    sws_scale(swsContext, frame->data, frame->linesize, 0, height, yuyvFrame.data, yuyvFrame.linesize);

    // 写入YUV数据到文件
    int yuyvSize = width * height * 2;
    outputFile.write(reinterpret_cast<const char*>(yuyvData), yuyvSize);

    // 清理资源
    sws_freeContext(swsContext);
    delete[] yuyvData;
}